Control Flow in Swift

Posted on 17 May, 2018 in Swift

Hello there,

This content is about control flow in swift.

If - Else

If-else statement allows us to use conditional statements in Swift.

let constantTen = 10
if(constantTen == 10){
  print("Oh, I know. It is 10") // print function allows us to print to console.
}else{
  print("I am not quite sure about that number")
}
// As you can image, it will print "Oh, I know. It is 10" to console.

For loop

For loop in Swift allows us to go through each element in an array.

let constantIntegerArray = [1,2,3,4] // Index starts from 0.
for element in constantIntegerArray {
  print(element) // prints each element to the console.
}
// But I want to know the index of that element. The next example is just for you. The following loop acts as the loop in C++.

let arraySize = constantIntegerArray.count // count gives us the size of the array.
for index in 0..<arraySize { // "n..<m" is from n to m-1. "n...m" is from n to m.
  print("\(index) - \(constantIntegerArray[index])") // \() allows us to break the string. Hence it allows us to write swift code inside of \()
}

While loop

While loop in Swift allows us to run code blocks until the condition in while does not check.

let constantIntegerArray = [1,2,3,4,5]
var counter = 0
while counter < constantIntegerArray.count {
  print(constantIntegerArray[counter]) // prints each element to the console.
  counter += 1 // Do not forget to increment the counter. If we do not increment it, this while loop goes to infinity
}

Some exercises

This exercise is taken from here. You can find more code examples in that repository, that I have covered in the iOS lecture.

  1. Print all numbers from 1 to 500, that is divisible by both 3 and 5.
  2. Print the number of decimal digits in an unsigned integer. For example, 9 has 1 digits. 123123 has 6 digits.

We will solve those question. However, I highly recommend you to solve the question first. Instead of looking the solutions first.

Solutions

One

// Defining the integer
let constantInteger = 500

// Looping through from 1 to 500
for i in 1...500{

  // Checking if the number is divisible by both 3 and 5
  if(i%3 == 0 && i%5 == 0){
    print(i)
  }

}

Two

// Defining the integer
let constantInteger = 1000

let stringVersionOfInteger = String(constantInteger) // This line changes integer to string. 0 -> "0", 100 -> "100"

print("\(stringVersionOfInteger.count)") // Printing the size of the integer string. "10" gives us 2. "1" gives us 1.